package Ai

import (
	"bytes"
	"crypto/tls"
	"encoding/json"
	// "fmt"
	"io"
	"net/http"
)


type ZhiPuReq struct {
	Model string `json:"model"`
	Message []map[string]string `json:"messages"`
	Stream bool `json:"stream"`
	Temperature float64 `json:"temperature"`
}

var client *http.Client


func init(){
	client = &http.Client{
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		},
	}
}


// DoSyncRequestContent 通用同步请求
// 其他使用默认值
// systemContent 系统消息
// userContent 用户消息
func DoSyncRequestContent(systemContent , userContent string)(string,error){
	return DoRequestContent(systemContent , userContent , false , 0.95)
}

// DoRequestMessage 简化通用请求
// systemContent 系统消息
// userContent 用户消息
// stream 是否开启流式
// temperature 回答随机值
func DoRequestContent(systemContent , userContent string , stream bool , temperature float64)(string,error){
	message := []map[string]string{
		{
			"role":"system",
			"content":systemContent,
		},
		{
			"role":"user",
			"content":userContent,
		},
	}
	return DoRequestMessages(message , stream , temperature)
}

// 通用请求
func DoRequestMessages(messages []map[string]string , stream bool , temperature float64)(string,error){
	param := ZhiPuReq{
			Model:"glm-4",
			Message:messages,
			Stream: stream,
			Temperature: temperature,
		}
	
	jsonData, err := json.Marshal(param)
    if err != nil {
		return "" , err
    }

    req, err := http.NewRequest("POST",constant.URL,  bytes.NewBuffer(jsonData))
    if err != nil {
		return "" , err
    }
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("Authorization", constant.ApiKey)
	
	resp, err := client.Do(req)
    if err != nil {
		return "" , err
    }
    defer resp.Body.Close()

    body, err := io.ReadAll(resp.Body)
    if err != nil {
		return "" , err
    }
	// fmt.Println(string(body))
	res := ZhiPuRes{}
	err = json.Unmarshal(body , &res)
	if err != nil && len(res.Choices) == 0{
		return "" , err
	}
	// fmt.Println(res)
    return res.Choices[0].Message.Content , nil
}

